package com.teatime.client.net.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.entity.AbstractHttpEntity;

public class MultiPartEntity extends AbstractHttpEntity {
	
	final private String MultpartContentType = "multipart/form-data; boundary=";

	private MultiPartInputStream mInStream;
	
	public MultiPartEntity() {
		super();
		mInStream = new MultiPartInputStream();
		setContentType(MultpartContentType + mInStream.getBoundary());
	}
	
	public void addPart(String name, FormFile file) {
		mInStream.addPart(name, file);
	}
	
	public void addPart(String name, String value) {
		mInStream.addPart(name, value);
	}

	public void addPart(String name, byte[] data) {
		mInStream.addPart(name, data);
	}
	
	@Override
	public InputStream getContent() throws IOException, IllegalStateException {
		// TODO Auto-generated method stub
		return mInStream;
	}

	@Override
	public long getContentLength() {
		// TODO Auto-generated method stub
		return mInStream.length();
	}

	@Override
	public boolean isRepeatable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isStreaming() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void writeTo(OutputStream os) throws IOException {
		// TODO Auto-generated method stub
		if (os == null) {
			throw new IllegalArgumentException("Output stream may not be null");
		}

		byte[] tmp = new byte[4096];
		int l;
		while ((l = mInStream.read(tmp)) != -1) {
			os.write(tmp, 0, l);
		}
		os.flush();
		
	}
	
}
